package com.atelier.plugin.database.ui;

import com.atelier.plugin.database.domain.*;
import com.atelier.plugin.database.util.ActionUtil;
import com.atelier.plugin.database.util.ConnectionInfoTreeUtil;
import com.atelier.plugin.tool.ProjectUtils;
import com.intellij.icons.AllIcons;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.project.Project;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.components.JBScrollPane;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.io.File;
import java.sql.SQLException;

/**
 * @author tangrufei
 * @date 2023-09-06 11:27
 */
@Data
public class DataBaseToolWindowContent
{
    public static Logger LOGGER=  LoggerFactory.getLogger(DataBaseToolWindowContent.class);

    private JPanel mainPanel;

    private JPanel actionsPanel;
    private JTree databaseTree;
    private JBScrollPane dataBaseScrollPane;

    private JLabel jLabel;
    private static DataBaseToolWindowContent instance;
    public DataBaseToolWindowContent() throws SQLException {
        init();
        ActionToolbar actionToolbar = ActionUtil.createActionToolbar("menuLocation", true, "com.atelier.plugin.action.database.menuGroup");
        actionToolbar.setTargetComponent(mainPanel);
        JComponent component = actionToolbar.getComponent();
        actionsPanel.add(component);
    }
    public void init() throws SQLException {

        Project project = ProjectUtils.getCurrProject();

//
        // 原生文件树组件
        ProjectView projectView  = ProjectView.getInstance(project);
       // ConnectionInfoTreeUtil.createConnectionInfoJTree(databaseTree);

        // 自动选择树中的任何节点
        databaseTree.setShowsRootHandles(true);
        // 设置自定义的渲染器
        databaseTree.setCellRenderer(new FileTreeCellRenderer());
        // 增加搜索功能
        new TreeSpeedSearch(databaseTree);
        ConnectionInfoTreeUtil.createConnectionInfoJTree(databaseTree);
        // 选择文件树显示的根节点
        databaseTree.setRootVisible(true);
        databaseTree.expandRow(0);
        databaseTree.setRootVisible(false);
      dataBaseScrollPane.setBorder(BorderFactory.createEmptyBorder());
      dataBaseScrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
//        databaseTree.setUI(new BasicTreeUI() {
//            @Override
//            public Rectangle getPathBounds(JTree tree, TreePath path) {
//                if (tree != null && treeState != null) {
//                    return getPathBounds(path, tree.getInsets(), new Rectangle());
//                }
//                return null;
//            }
//
//            private Rectangle getPathBounds(
//                    TreePath path, Insets insets, Rectangle bounds) {
//                Rectangle rect = treeState.getBounds(path, bounds);
//                if (rect != null) {
//                    rect.width = tree.getWidth();
//                    rect.y += insets.top;
//                }
//                return rect;
//            }
//        });

    }

    private  class FileTreeCellRenderer extends DefaultTreeCellRenderer {
        public FileTreeCellRenderer()  {
            setBorder(null); // 移除默认边框
        }
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                super.getTreeCellRendererComponent(
                    tree, value, selected, expanded, leaf, row, hasFocus);
            // 如果当前节点被选中，设置整行高亮
               setBorderSelectionColor(getBackgroundSelectionColor());

//              if (selected) {
//                 setBackground(tree.getBackground());
//                 setForeground(tree.getForeground());
//            } else {
//                setBackground(tree.getBackground());
//                setForeground(tree.getForeground());
//            }
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object userObject = node.getUserObject();
                Boolean toolTipTextCanRemove=true;
                if (userObject instanceof DatabaseConnectionInfo) {
                    DatabaseConnectionInfo info = (DatabaseConnectionInfo) userObject;
                    setIcon(info.getDatabaseType().getIcon());
                    setText(info.getName());
                }
                if(userObject instanceof TableInfo){
                    TableInfo info = (TableInfo) userObject;
                    setIcon(Icons.TABLE);
                    setText(info.getTableName());
                    setToolTipText(info.getRemark());
                    toolTipTextCanRemove=false;
                }
                if(userObject instanceof ColumnInfo){
                    ColumnInfo info = (ColumnInfo) userObject;
                    setIcon(Icons.COLUMN);
                    setText("<html>" + info.getColumnName()+"  "+"<font size='-4' color='C1C3C7'>"+info.getTypeName().toLowerCase()+"</font></html>");
                    setToolTipText(info.getRemark());
                }else if(toolTipTextCanRemove){
                    setToolTipText("");
                }
                if(userObject instanceof Schema){
                    Schema info = (Schema) userObject;
                    setIcon(Icons.SCHEMA);
                    setText(info.getName());
                }
                if(userObject instanceof Columns){
                    Columns info = (Columns) userObject;
                    setIcon(AllIcons.Modules.SourceRoot);
                    setText(info.getName());
                }
                if(userObject instanceof Tables){
                    Tables info = (Tables) userObject;
                    setIcon(AllIcons.Modules.SourceRoot);
                    setText(info.getName());
                }
                if(userObject instanceof Keys){
                    Keys info = (Keys) userObject;
                    setIcon(AllIcons.Modules.SourceRoot);
                    setText(info.getName());
                }
                if(userObject instanceof Key){
                    Key info = (Key) userObject;
                    setIcon(Icons.GOLDY);
                    setText(info.getColumn().getColumnName());
                }

            }
            setBorder(BorderFactory.createEmptyBorder());
            tree.setBorder(BorderFactory.createEmptyBorder());
            dataBaseScrollPane.setBorder(BorderFactory.createEmptyBorder());
            //LOGGER.info("触发");
            return this;
        }
    }
    /**
     * 返回创建的JPanel
     * @return JPanel
     */
    public JPanel getContent() {
        System.out.println("getContent");
        return mainPanel;
    }

    public static DataBaseToolWindowContent getInstants() throws SQLException {
        if (instance == null) {
            instance = new DataBaseToolWindowContent();
        }
        return instance;
    }

}
